import json
import logging
import traceback
import uuid
import tornado.websocket
from radiocaca_manager import radiocaca_manager


class RadiocacaHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        self.m_id = str(uuid.uuid4())
        radiocaca_manager.register(self.m_id, self)

    def on_message(self, message):
        logging.info("on_message: " + message)
        j_msg = json.loads(message)
        if j_msg["key"] == "hello":
            for key, item in radiocaca_manager.last_data.items():
                if item:
                    # key->func: 加上update_
                    self.send_msg("update_" + key, item)
        else:
            radiocaca_manager.update_database(j_msg["key"], j_msg["data"])

    def on_close(self):
        radiocaca_manager.unregister(self.m_id)

    def send_msg(self, key, msg):
        logging.info("" + key)
        try:
            str_msg = str(json.dumps({"key": key, "data": msg}))
            self.write_message(str_msg)
        except:
            traceback.print_exc()
